package com.xbai.user.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.xbai.entity.BCrypt;
import com.xbai.entity.JwtUtil;
import com.xbai.entity.Result;
import com.xbai.entity.StatusCode;
import com.xbai.user.pojo.User;
import com.xbai.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @desc UserController
 * @author jxbai
 * @date 2021/1/28
 */

@RestController
@RequestMapping("/user")
@CrossOrigin
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final UserService userService;

    @GetMapping("/load/{id}")
    public Result<User> findByUsername(@PathVariable(name = "id") String id) {
        //调用UserService实现根据主键查询User
        User user = userService.findById(id);
        return new Result<>(true, StatusCode.OK, "查询成功", user);
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletResponse response) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return new Result(false, StatusCode.LOGIN_ERROR, "用户名或密码不能为空");
        }
        //查询用户信息
        User loginUser = userService.findById(user.getUsername());
        if (loginUser == null || !BCrypt.checkpw(user.getPassword(), loginUser.getPassword())) {
            return new Result(false, StatusCode.LOGIN_ERROR, "用户名或密码错误");
        }
        //设置令牌信息
        Map<String,Object> info = new HashMap<>();
        info.put("role", "USER");
        info.put("success", "SUCCESS");
        info.put("username", user.getUsername());
        // 生成令牌
        String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(info), null);

        //每次登录的时候，添加令牌信息到Cookie中
        Cookie cookie = new Cookie("Authorization", jwt);
        response.addCookie(cookie);
        //3.设置头文件中
        response.setHeader("Authorization", jwt);
        return new Result(true, StatusCode.OK, "登录成功", jwt);
    }

    /***
     * User分页条件搜索实现
     * @param user {@link User}
     * @param page 页码
     * @param size 页大小
     * @return {@link Result<PageInfo>}
     */
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@RequestBody(required = false) User user, @PathVariable  int page, @PathVariable  int size){
        //调用UserService实现分页条件查询User
        PageInfo<User> pageInfo = userService.findPage(user, page, size);
        return new Result<>(pageInfo);
    }

    /***
     * User分页搜索实现
     * @param page 页码
     * @param size 页大小
     * @return {@link Result<PageInfo>}
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@PathVariable  int page, @PathVariable  int size){
        //调用UserService实现分页查询User
        PageInfo<User> pageInfo = userService.findPage(page, size);
        return new Result<>(pageInfo);
    }

    /***
     * 多条件搜索User数据
     * @param user {@link User}
     * @return {@link Result}
     */
    @PostMapping(value = "/search" )
    public Result<List<User>> findList(@RequestBody(required = false) User user){
        //调用UserService实现条件查询User
        List<User> list = userService.findList(user);
        return new Result<>(list);
    }

    /***
     * 根据ID删除User数据
     * @param id 主键id
     * @return {@link Result}
     */
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable String id){
        //调用UserService实现根据主键删除
        userService.delete(id);
        return new Result();
    }

    /***
     * 修改User数据
     * @param user {@link User}
     * @param id 主键id
     * @return {@link Result}
     */
    @PutMapping(value="/{id}")
    public Result update(@RequestBody User user, @PathVariable String id){
        //设置主键值
        user.setUsername(id);
        //调用UserService实现修改User
        userService.update(user);
        return new Result();
    }

    /***
     * 新增User数据
     * @param user {@link User}
     * @return {@link Result}
     */
    @PostMapping
    public Result add(@RequestBody User user){
        //调用UserService实现添加User
        userService.add(user);
        return new Result();
    }

    /***
     * 根据ID查询User数据
     * @param id 主键id
     * @return {@link Result}
     */
    @GetMapping("/{id}")
    public Result<User> findById(@PathVariable String id){
        //调用UserService实现根据主键查询User
        User user = userService.findById(id);
        return new Result<>(user);
    }

    /***
     * 查询User全部数据
     * @return {@link Result}
     */
    @GetMapping
    public Result<List<User>> findAll(HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        log.info("令牌信息：{}", authorization);
        //调用UserService实现查询所有User
        List<User> list = userService.findAll();
        return new Result<>(list) ;
    }
}
